package com.study.lxy.zookeeper;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ZookeeperClient {

    private static final Logger logger = LoggerFactory.getLogger(ZookeeperClient.class);

    public static volatile CountDownLatch connectLatch = new CountDownLatch(1);

    public static ZooKeeper connect(String url, int sessionTimeOut) throws Exception{

        ZooKeeper zooKeeper = new ZooKeeper(url, sessionTimeOut, new ConnectWatcher());
        try {
            connectLatch.await(2000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            throw new Exception("连接超时");
        }
        return zooKeeper;

    }

    static class ConnectWatcher implements Watcher{

        public void process(WatchedEvent watchedEvent) {
            logger.info("event type = {}",watchedEvent.getType());
            if(Event.EventType.None == watchedEvent.getType()){
                logger.info("connect successful.");
                connectLatch.countDown();
            }

        }
    }
}
